package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.Util.EventMsgCode;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.View.CommonPopWindow;
import com.ohuang.jiaxiaotong.View.PickerScrollView;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ArrayStringItem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

//给课程表添加课程界面
public class AddCourseActivity extends BaseAc {
    private String CourseName = "";
    private String teacher = "";
    private int Pos, Code;
    private EditText editText_CourseName, editText_teacher;
    private TextView textView;
    private int day_code, num_code;
    private String dayOfWeek[] = {"周一", "周二", "周三", "周四", "周五"};
    private ArrayList<ArrayStringItem> Data_day, Data_num;
    private String numOfDay[] = {"第一节", "第二节", "第三节", "第四节", "第五节", "第六节", "第七节", "第八节"};
    private String txt_day, txt_num;
    private String className;
    private User user;
    private static final int RE_SUCCESS = 0, RE_FAIL = 1, RE_ERROR = 2, RE_OTHER = 3;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_course);
        EventBus.getDefault().register(this);
        Ohuang.changeStatusBarTextImgColor(this, true);//设置手机状态栏字体为黑
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮

        setTitle("编辑课程");
        Intent intent = getIntent();
        Code = intent.getIntExtra("code", 0);
        className = intent.getStringExtra("className");

        if (Code == 1) {
            String a = intent.getStringExtra("courseName");
            try {
                String[] b = a.split("@");

                CourseName = b[0].replaceAll("\r|\n", "");

                teacher = b[1];
            } catch (Exception e) {
                CourseName = intent.getStringExtra("courseName");
            }

        }
        Pos = intent.getIntExtra("pos", 0);
        initView();

    }

    private void initView() {
        editText_CourseName = findViewById(R.id.edit_courseName_addCourse);
        editText_teacher = findViewById(R.id.edit_teacher_addCourse);
        if (!CourseName.isEmpty()) {
            editText_CourseName.setText(CourseName);
        }
        if (!teacher.isEmpty()) {
            editText_teacher.setText(teacher);
        }

        day_code = Pos % 5;
        num_code = Pos / 5;

        Data_day = new ArrayList<>();
        Data_num = new ArrayList<>();
        for (int i = 0; i < dayOfWeek.length; i++) {
            Data_day.add(i, new ArrayStringItem(i, dayOfWeek[i]));
        }
        for (int i = 0; i < numOfDay.length; i++) {
            Data_num.add(i, new ArrayStringItem(i, numOfDay[i]));
        }
        textView = findViewById(R.id.txt_numCourse_addCourse);
        txt_day = dayOfWeek[day_code];
        txt_num = numOfDay[num_code];
        textView.setText(txt_day + "   " + txt_num);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int screenHeigh = getResources().getDisplayMetrics().heightPixels;

                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_picker_selector_bottom)
//                .setAnimationStyle(R.style.AppTheme)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(ViewGroup.LayoutParams.MATCH_PARENT, Math.round(screenHeigh * 0.3f))
                        .setViewOnClickListener(CPWClickListener)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .setBackgroundDrawable(new ColorDrawable(999999))
                        .build(AddCourseActivity.this)
                        .showAsBottom(v);
            }
        });
    }

    CommonPopWindow.ViewClickListener CPWClickListener = new CommonPopWindow.ViewClickListener() {
        @Override
        public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
            switch (mLayoutResId) {
                case R.layout.pop_picker_selector_bottom:
                    TextView imageBtn = view.findViewById(R.id.img_guanbi);
                    PickerScrollView addressSelector = view.findViewById(R.id.address);
                    PickerScrollView addressSelector2 = view.findViewById(R.id.address2);
                    // 设置数据，默认选择第一条
                    addressSelector.setData(Data_day);
//                    addressSelector.setSelected(day_code);

                    addressSelector2.setData(Data_num);
//                   addressSelector2.setSelected(num_code);
                    //滚动监听
                    addressSelector.setOnSelectListener(new PickerScrollView.onSelectListener() {
                        @Override
                        public void onSelect(ArrayStringItem arrayStringItem) {
                            txt_day = arrayStringItem.getS();
                            day_code = arrayStringItem.getPosition();
                            textView.setText(txt_day + "   " + txt_num);
                        }
                    });

                    addressSelector2.setOnSelectListener(new PickerScrollView.onSelectListener() {
                        @Override
                        public void onSelect(ArrayStringItem arrayStringItem) {
                            txt_num = arrayStringItem.getS();
                            num_code = arrayStringItem.getPosition();
                            textView.setText(txt_day + "   " + txt_num);
                        }
                    });

                    //完成按钮
                    imageBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPopupWindow.dismiss();
                        }
                    });
                    break;
            }

        }
    };


    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;

    }

    //按钮 添加课程
    public void AddCourseClick(View view) {
        if (Sys.isClick()) {
            CourseName = editText_CourseName.getText().toString();
            teacher = editText_teacher.getText().toString();
            dialogLoading = Ohuang.dialogLoadingshow(this, "正在更改课表");

            httpUpdateCourse();//发送更改请求

        }
    }

    private void httpUpdateCourse() {
        HashMap<String, String> map = new HashMap<>();
        map.put("course", (num_code + 1) + "");
        map.put("week", (day_code + 1) + "");
        map.put("grade", CourseName);
        map.put("className", className);
        map.put("teacher", teacher);
        map.put("username", user.getUsername());
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "teacher/fillTimetable", map, new CallBackString() {
            @Override
            public void fail(String s) {
                myHandler.sendEmptyMessage(RE_ERROR);
            }
            @Override
            public void success(String ojb) {
                if ("success".equals(ojb)) {
                    myHandler.sendEmptyMessage(RE_SUCCESS);
                } else if ("error".equals(ojb)) {
                    myHandler.sendEmptyMessage(RE_FAIL);
                } else {
                    myHandler.sendEmptyMessage(RE_OTHER);
                }
            }
        });


    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case RE_SUCCESS:
                    dialogLoading.dismiss();
                    EventBus.getDefault().postSticky(new EventMsg(EventMsgCode.CODE_3, "通知课程表刷新"));
                    Ohuang.dialogshow(AddCourseActivity.this, "更改成功", "课程数据已更新");
                    break;

                default:
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(AddCourseActivity.this, "更改失败", "课程更新失败,请检查网络");
                    break;

            }
        }
    };
}
